/*
 * Copyright (c) 2007 OpenNETCF Consulting, LLC
 * 
 * OpenNETCF MITx11 License
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
 * associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial 
 * portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT 
 * OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using WIAVIDEOLib;
using WIALib;

namespace OpenNETCF.Wia
{
    public sealed class Camera : IComparable<Camera>, IDisposable
    {
        private DeviceInfo m_device;
        private WiaVideo m_video;
        private object m_videoLock = new object();

        private volatile bool m_disposed = false;
        private string m_name;
        private string m_port;
        private string m_manufacturer;
        private string m_id;
        private string m_type;
        private string m_clsid;
        private Control m_displayWindow;
        private int m_index;

        internal Camera(DeviceInfo deviceInfo, int index)
        {
            m_device = deviceInfo;

            m_name = m_device.Name;
            m_manufacturer = m_device.Manufacturer;
            m_id = m_device.Id;
            m_type = m_device.Type;
            m_clsid = m_device.UIClsid;
            m_port = m_device.Port;
            m_index = index;
        }

        internal void Disconnect()
        {
            Release();
        }

        #region --- Dispose ---
        
        private void Release()
        {
            if (m_device != null)
            {
                Marshal.ReleaseComObject(m_device);
                m_device = null;
            }

            lock (m_videoLock)
            {
                if (m_video != null)
                {

                    try
                    {
                        Marshal.ReleaseComObject(m_video);
                    }
                    catch (Exception ex) { }
                    m_video = null;
                }
            }

        }

        private void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                if (disposing)
                {
                    // add any managed disposition here if we ever need it
                }

                Release();
                m_disposed = true;
            }
        }

        ~Camera()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

        private bool InitializeVideo()
        {
            return InitializeVideo(IntPtr.Zero);
        }

        private bool InitializeVideo(IntPtr display)
        {
            if (m_video != null) return true;

            lock (m_videoLock)
            {
                m_video = new WiaVideoClass();
                m_video.ImagesDirectory = Path.GetTempPath();
                m_video.PreviewVisible = 0;

                try
                {
                    if (display == IntPtr.Zero)
                    {
                        m_video.CreateVideoByWiaDevID(this.ID, IntPtr.Zero, 0, 1);
                    }
                    else
                    {
                        m_video.CreateVideoByWiaDevID(this.ID, display, 1, 1);
                    }
                }
                catch (COMException ex)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("WIA IntitializeVideo failed with 0x{0:x8}", ex.ErrorCode));
                    m_video.DestroyVideo();
                    m_video = null;
                    unchecked
                    {
                        if (ex.ErrorCode == (int)0x80040217)
                        {
                            throw new CameraInitializationException("Camera Inititialization failed.  Try disconnecting and reconnecting the cameras", ex);
                        }
                    }
                    // hresults: 
                    // 0x80040217 == Cannot Connect
                    // 0x80070002 == file not found
                    // 0x800705AA == insufficient resources
                    return false;
                }
                return true;
            }
        }

        public bool Playing
        {
            get
            {
                if (m_video == null) return false;
                return m_video.GetCurrentState() == WIAVIDEO_STATE.WIAVIDEO_VIDEO_PLAYING;
            }
        }

        public void Play()
        {
            if (m_video == null) InitializeVideo();
            lock (m_videoLock)
            {
                if (!Playing) m_video.Play();
            }
        }

        public void Pause()
        {
            lock (m_videoLock)
            {
                if (Playing) m_video.Pause();
            }
        }

        public int Index
        {
            get { return m_index; }
            internal set { m_index = value; }
        }

        public Control DisplayWindow
        {
            set
            {
                m_displayWindow = value;
                if (m_video != null)
                {
                    lock (m_videoLock)
                    {
                        // tear down video
                        m_video.DestroyVideo();
                        m_video = null;
                    }
                }
                if (m_displayWindow != null)
                {
                    InitializeVideo(m_displayWindow.Handle);
                    lock (m_videoLock)
                    {

                        m_video.PreviewVisible = 1;
                    }
                }
            }
            get
            {
                return m_displayWindow;
            }
        }

        public Image GrabFrame()
        {
            if (!IsConnected)
            {
                throw new CameraDisconnectedException(this);
            }
            // make sure video is running
            if (!InitializeVideo(IntPtr.Zero))
            {
                return null;
            }

            // TODO: may have to Play here
            bool wasPlaying = Playing;
            if (!wasPlaying)
            {
                Play();

                int timeout = 0;
                // wait for it to spin up
                while (!Playing)
                {
                    System.Threading.Thread.Sleep(10);
                    // wait up to 1 second
                    if (timeout++ > 100)
                    {
                        throw new Exception("Unable to start camera");
                    }
                }
            }

            // take a picture
            string fileName;
            lock (m_videoLock)
            {
                m_video.TakePicture(out fileName);
            }
            if (!wasPlaying) Pause();

            // create an image from the file
            return Bitmap.FromFile(fileName);
        }

        public bool IsConnected
        {
            get { return m_device != null; }
        }

        public string ID
        {
            get { return m_id; }
        }

        public string Manufacturer
        {
            get { return m_manufacturer; }
        }

        public string Name
        {
            get { return m_name; }
        }

        public string Port
        {
            get { return m_port; }
        }

        public string Type
        {
            get { return m_type; }
        }

        public string Clsid
        {
            get { return m_clsid; }
        }

        public override string ToString()
        {
            return this.Name;
        }

        public override bool Equals(object obj)
        {
            Camera info = obj as Camera;
            if (info == null) return false;

            if (string.Compare(info.ID, this.ID) != 0) return false;
            if (string.Compare(info.Name, this.Name) != 0) return false;
            if (string.Compare(info.Manufacturer, this.Manufacturer) != 0) return false;
            if (string.Compare(info.Port, this.Port) != 0) return false;
            if (string.Compare(info.Type, this.Type) != 0) return false;

            return true;
        }

        public override int GetHashCode()
        {
            return (ID.GetHashCode() | Manufacturer.GetHashCode() | Name.GetHashCode()
            | Port.GetHashCode() | Type.GetHashCode());
        }

        public int CompareTo(Camera other)
        {
            // order by name, manufacture, Port, Type
            int comp = string.Compare(Name, other.Name, true);
            if (comp != 0) return comp;

            comp = string.Compare(Manufacturer, other.Manufacturer, true);
            if (comp != 0) return comp;

            comp = string.Compare(Port, other.Port, true);
            if (comp != 0) return comp;

            return string.Compare(Type, other.Type, true);
        }
    }
}
